package cn.wolfcode.redis.service.impl;

import cn.wolfcode.entity.Userinfo;
import cn.wolfcode.exception.LogicException;
import cn.wolfcode.redis.service.IUserInfoRedisService;
import cn.wolfcode.redis.util.RedisKeys;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.netty.util.internal.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class UserInfoRedisService implements IUserInfoRedisService {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    public void setVerifyCode(String phone, String code) {
        String key = RedisKeys.REGIST_VERIFY_CODE.join(phone);
        stringRedisTemplate.opsForValue()
                .set(key, code, RedisKeys.REGIST_VERIFY_CODE.getTime(), TimeUnit.SECONDS);
    }

    @Override
    public String getVerifyCode(String phone) {
        String key = RedisKeys.REGIST_VERIFY_CODE.join(phone);
        return stringRedisTemplate.opsForValue().get(key);
    }

    @Override
    public String setToken(Userinfo userInfo) {
        String token = UUID.randomUUID().toString().toString().replace("-", "");
        String key = RedisKeys.USER_LOGIN_TOKEN.join(token);
        String value = JSONObject.toJSONString(userInfo);
        stringRedisTemplate.opsForValue().set(key, value, RedisKeys.USER_LOGIN_TOKEN.getTime(), TimeUnit.SECONDS);
        return token;
    }

    @Override
    public Userinfo getUserByToken(String token) {
        if (!StringUtils.hasLength(token)) {
            return null;
        }
        String key = RedisKeys.USER_LOGIN_TOKEN.join(token);
        if (stringRedisTemplate.hasKey(key)) {
            return JSON.parseObject(stringRedisTemplate.opsForValue().get(key), Userinfo.class);
        }
        return null;
    }
}
